<?php
/**
 * Created by PhpStorm.
 * User: bevan
 * Date: 2018/1/2
 * Time: 下午3:12
 */

namespace app\user\model;

use think\Model;
use think\Loader;
use thans\auth\facade\Auth;
use thans\auth\model\AuthGroupAccessModel;
use thans\auth\model\AuthGroupModel;
use app\common\model\MenuModel;

class UserModel extends Model
{
    private $_pk = 'id';
    protected $readonly = ['user_login', 'create_time'];
    protected $type = [
        'birthday' => 'timestamp:Y-m-d',
        'last_login_time' => 'timestamp:Y-m-d H:i:s',
    ];

    /**
     * 根据用户id获取某个用户的用户组
     * @param $auth_group_access
     * @param $auth_group
     * @param $uid
     * @return mixed
     */
    public function getUserGroups($uid)
    {
        $auth_group_access = 'auth_group_access';
        $auth_group_access = Loader::parseName($auth_group_access, 1);
        $auth_group = 'auth_group';
        $auth_group = Loader::parseName($auth_group, 1);

        $user_groups = $this->view($auth_group_access, 'uid,group_id')
            ->view($auth_group, 'title,rules', "{$auth_group_access}.group_id={$auth_group}.id", 'LEFT')
            ->where("{$auth_group_access}.uid='{$uid}' and {$auth_group}.status='1'")
            ->find();

        return $user_groups;
    }

    /**
     * 获取用户信息
     * @param $uid
     * @return mixed
     */
    public function getUserInfo($uid)
    {
        static $userinfo = [];

        // 获取用户表主键
        if (!isset($userinfo[$uid])) {
            $userinfo[$uid] = $this->where($this->_pk, $uid)->find();
        }
        return $userinfo[$uid];
    }

    /**
     *
     * @method 获取所有的用户
     * @version
     * @User: bevan
     * @return
     */
    public function getList($page, $num, $type = [], $keyword = '')
    {
        $userModel = $type ? $this->where('user_type', 'in', $type) : $this;
        $userModel = $keyword ? $userModel->where('user_login|user_email|mobile', 'LIKE', '%' . $keyword . '%') : $userModel;
        $total = clone $userModel;
        $total = $total->count();
        $userModel = $userModel->field('user_pass', true);
        $users = $userModel->page($page, $num)
            ->order('create_time', 'desc')
            ->select();
        return ['code' => 1001, 'msg' => 'success', 'data' => $users, 'total' => $total];
    }

    /**
     *
     * @method
     * @version
     * @User: bevan
     * @param $id
     * @return
     */
    public function userMenu($id)
    {
        $menuModel = new MenuModel();

        $groups = Auth::getGroups($id);
        if (!$groups) {
            return [];
        }
        if ($groups['group_id'] == 1) {
            return $menuModel->getTreeList();
        } else {
            $rules = $groups['rules'];
            $rule_arr = explode(',', $rules);
        }
        $menus = $menuModel->getTreeList($rule_arr);
        return $menus;
    }

    /**
     *
     * @method 带有角色组详情的个人信息
     * @version
     * @User: bevan
     * @param $id
     * @param bool $checked
     * @return
     */
    public function userRuleDetail($id, $checked = true)
    {
        $user = $this->field('user_pass,last_login_ip', true)->find($id);

        if ($user === false) {
            return false;
        }

        //所有的权限组
        $user_groups = AuthGroupAccessModel::where('uid', $id)
            ->alias('aga')
            ->join('auth_group ag', 'ag.id = aga.group_id')
            ->select();

        $user_groups_arr = [];

        foreach ($user_groups as $user_group) {
            $user_groups_arr[] = $user_group['group_id'];
        }

        $user_groups_arr = array_unique($user_groups_arr);

        $all_groups = AuthGroupModel::all();

        foreach ($all_groups as $key => &$group) {
            if (in_array($group['id'], $user_groups_arr)) {
                $group['checked'] = 1;
            } else {
                if ($checked) {
                    $group['checked'] = 0;
                } else {
                    unset($all_groups[$key]);
                }
            }
        }

        $user['groups'] = $all_groups;
        return $user;
    }

    /**
     * 每一次都需要初始化 user_sql 对象
     * @method 验证用户名 邮箱 手机号码是否唯一 (注: 优先经过validate验证器调用过后再使用) 排除自身
     * @version
     * @User: bevan
     * @param $data
     * @return 验证信息
     */
    public static function checkUnique($data, $id = '')
    {
        //验证用户名是否唯一
        $validate_msg = true;
        foreach ($data as $field_key => $field_value) {
            $switch_msg = true;
            switch ($field_key) {
                case 'user_login':
                    if ($id) {
                        $user_sql = self::where('id', '<>', $id);  // 非创建时候的验证 排除自身
                    } else {
                        $user_sql = self::where('1=1');// 创建时候的验证
                    }
                    $user = $user_sql->where($field_key, $field_value)->find();
                    if ($user) {
                        $switch_msg = '用户名已经存在';
                    }
                    break;
                case 'user_email':
                    if ($field_value != '') {
                        if ($id) {
                            $user_sql = self::where('id', '<>', $id);  // 非创建时候的验证 排除自身
                        } else {
                            $user_sql = self::where('1=1');// 创建时候的验证
                        }
                        $user = $user_sql->where($field_key, $field_value)->find();
                        if ($user) {
                            $switch_msg = '该邮箱已经注册';
                        }
                    }
                    break;
                case 'mobile':
                    if ($id) {
                        $user_sql = self::where('id', '<>', $id);  // 非创建时候的验证 排除自身
                    } else {
                        $user_sql = self::where('1=1');// 创建时候的验证
                    }
                    $user = $user_sql->where($field_key, $field_value)->find();
                    if ($user) {
                        $switch_msg = '该手机号码已经注册';
                    }
                    break;
                default:
                    $switch_msg = true;
                    break;
            }

            if ($switch_msg !== true) {
                //终止循环
                $validate_msg = $switch_msg;
                break;
            }
        }

        return $validate_msg;
    }

    //获取指定日期内的用户数
    public function getNewUsersCountByTimes($start, $end)
    {
        return $this->field('user_login')->where('create_time', 'between', [$start, $end])->count();
    }
}
